package org.minuframework.file.upload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.minuframework.lang.StringUtils;
import org.minuframework.encrypt.BASE64U;
import org.minuframework.exception.ExceptionFailed;

import com.google.common.collect.Lists;

@Deprecated
public class DefaultFileUpload extends AbstractFileBuilder implements FileUploadFactory {
    
    public DefaultFileUpload(FileParamerConfigurer fileParamerConfigurer, FileTypesConfigurer fileTypesConfigurer, String charset) {
        super(fileParamerConfigurer, fileTypesConfigurer, charset);
    }
    
    // ------------------------------------------------------------------------
    
    // ------------------------------------------------------------------------
    
    public String fileUpload(HttpServletRequest request, FileUploadType type) {
        StringBuilder result = new StringBuilder();
        
        // 当前表单是否为文件上传表单
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                ServletFileUpload upload = getServletFileUpload();
                List<FileItem> items = upload.parseRequest(request); // 把请求数据转换为list集合
                result.append(fileUpload(items.get(0), type));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        return result.toString();
    }
    
    public List<String> fileUploadList(HttpServletRequest request, FileUploadType type) {
        List<String> result = Lists.newArrayList();
        
        // 当前表单是否为文件上传表单
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                ServletFileUpload upload = getServletFileUpload();
                List<FileItem> items = upload.parseRequest(request); // 把请求数据转换为list集合
                result = fileUpload(items, type);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        return result;
    }
    
    public String fileUpload(FileItem item, FileUploadType type) throws ExceptionFailed {
        StringBuilder result = new StringBuilder();
        
        if (StringUtils.isNotEmpty(item.getName())) {
            File file = getFile(item.getName(), type);
            if (isFile(file)) {
                try {
                    String param = randomUUId(item.getName());
                    File realpath = new File(file, param);
                    fileUpload(item.getInputStream(), realpath);
                    result.append(param);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                throw new ExceptionFailed("Cannot find folder form " + file);
            }
        }
        
        return result.toString();
    }
    
    public List<String> fileUpload(List<FileItem> items, FileUploadType type) throws ExceptionFailed {
        List<String> result = Lists.newArrayList();
        for (FileItem item : items) {
            if (!item.isFormField()) {
                String param = fileUpload(item, type);
                if (StringUtils.isNotEmpty(param)) {
                    result.add(param);
                }
            }
        }
        return result;
    }
    
    public String fileUpload(InputStream in, File file) {
        StringBuilder result = new StringBuilder();
        
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        return result.toString();
    }
    
    // ------------------------------------------------------------------------
    
    @Override
    public String fileUploadBase64(byte[] imgstr, FileUploadType type) throws ExceptionFailed {
        StringBuilder result = new StringBuilder();
        
        String preffix = BASE64U.suffix(imgstr);
        File file = getFile(preffix, type);
        if (isFile(file)) {
            String param = randomUUId() + preffix;
            File realpath = new File(file, param);
            if (BASE64U.generateImage(imgstr, realpath)) {
                result.append(param);
            }
        } else {
            throw new ExceptionFailed("Cannot find folder form " + file);
        }
        
        return result.toString();
    }
    
    @Override
    public String fileUploadBase64(byte[] imgstr, String type) throws ExceptionFailed {
        StringBuilder result = new StringBuilder();
        
        String preffix = BASE64U.suffix(imgstr);
        File file = getFile(preffix, type);
        if (isFile(file)) {
            String param = randomUUId() + preffix;
            File realpath = new File(file, param);
            if (BASE64U.generateImage(imgstr, realpath)) {
                result.append(param);
            }
        } else {
            throw new ExceptionFailed("Cannot find folder form " + file);
        }
        
        return result.toString();
    }
    
    @Override
    public String fileUploadBase64(String imgstr, FileUploadType type) throws ExceptionFailed {
        StringBuilder result = new StringBuilder();
        
        String prefix = BASE64U.suffix(imgstr);
        File file = getFile(prefix, type);
        if (isFile(file)) {
            String param = randomUUId() + prefix;
            File realpath = new File(file, param);
            if (BASE64U.generateImage(imgstr, realpath)) {
                result.append(param);
            }
        } else {
            throw new ExceptionFailed("Cannot find folder form " + file);
        }
        
        return result.toString();
    }
    
    @Override
    public String fileUploadBase64(String imgstr, String type) throws ExceptionFailed {
        StringBuilder result = new StringBuilder();
        
        String preffix = BASE64U.suffix(imgstr);
        File file = getFile(preffix, type);
        if (isFile(file)) {
            String param = randomUUId() + preffix;
            File realpath = new File(file, param);
            if (BASE64U.generateImage(imgstr, realpath)) {
                result.append(param);
            }
        } else {
            throw new ExceptionFailed("Cannot find folder form " + file);
        }
        
        return result.toString();
    }
    
    @Override
    public List<String> fileUploadBase64(List<String> imgstr, FileUploadType type) throws ExceptionFailed {
        List<String> result = Lists.newArrayList();
        for (String string : imgstr) {
            String param = fileUploadBase64(string, type);
            if (StringUtils.isNotEmpty(param)) {
                result.add(param);
            }
        }
        return result;
    }
    
    @Override
    public List<String> fileUploadBase64(List<String> imgstr, String type) throws ExceptionFailed {
        List<String> result = Lists.newArrayList();
        for (String string : imgstr) {
            String param = fileUploadBase64(string, type);
            if (StringUtils.isNotEmpty(param)) {
                result.add(param);
            }
        }
        return result;
    }
    
    // ------------------------------------------------------------------------
    
    // ------------------------------------------------------------------------
    
    public ServletFileUpload getServletFileUpload() {
        return getServletFileUpload(100 * 1024 * 1024, 100 * 1024 * 1024, charset);
    }
    
    public static ServletFileUpload getServletFileUpload(long fileSizeMax, long sizeMax, String encoding) {
        FileItemFactory factory = new DiskFileItemFactory(); // 文件上传工厂
        ServletFileUpload upload = new ServletFileUpload(factory); // 文件上传核心工具类
        
        upload.setFileSizeMax(fileSizeMax);
        upload.setSizeMax(sizeMax);
        upload.setHeaderEncoding(encoding);
        
        return upload;
    }
    
}
